package com.whuan.student.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * Created by 廖师兄
 * 2018-02-21 10:40
 */
public class JsonUtil {

	private static ObjectMapper objectMapper = new ObjectMapper();

	/**
	 * 对象转换为json字符串
	 * @param object
	 * @return
	 */
	public static String toJson(Object object) {
		try {
			return objectMapper.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * create by: whaun
	 * create date:  2019/8/10 time:9:05
	 * description:json 转 对象
	 */
     public static Object fromJson(String string,Class classType){
		 try{
		 	return objectMapper.readValue(string,classType);
		 }catch (IOException e){
		 	e.printStackTrace();
		 }
		 return null;
	 }
    /**
     * create by: whaun
     * create date:  2019/8/10 time:9:05
     * description:json 转 list、map 之类的时
     */
    public static Object fromJson(String string, TypeReference typeReference){
        try{
            return objectMapper.readValue(string,typeReference);
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    /*使用方式
    *List<ProductInfoOutput> ProductInfoOutputList = (TypeReference)JsonUtil.fromJson(message,
    *                               new  TypeReference<List<ProductInfoOutput>>(){});
    *
    *
    * */
}
